package com.app.micaihu.view.newsdetail.view;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.app.micaihu.bean.game.GameContent;
import com.app.micaihu.configure.StyleConstant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.custom.view.web.CustomWebViewDownLoadListener;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.micaihu.view.user.usertask.UserTaskActivity;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.utils.util.AppTools;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 加载新闻的webview
 * Created by linkai on 2016/7/19.
 */
public class NewsDetailWebView extends WebView {

    private OnViewSizeChangedListener mOnViewSizeChangedListener;
    private int mContentHeight;//内容高度
    private boolean isDestory;


    public OnViewSizeChangedListener getmOnViewSizeChangedListener() {
        return mOnViewSizeChangedListener;
    }

    public void setOnViewSizeChangedListener(OnViewSizeChangedListener listener) {
        this.mOnViewSizeChangedListener = listener;
    }


    @Override
    public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String failUrl) {
        if (isDestory) {
            return;
        }
        if (TextUtils.isEmpty(data)) {
            super.loadDataWithBaseURL(baseUrl, "", mimeType, encoding, failUrl);
            return;
        }
        String fontStyle = "* {font-size:" + (20) + "px;line-height:" + (30) + "px;} ";
        String webStyle;
        //日间模式
        String webHeadStyle = StyleConstant.STYLE_ONE + fontStyle + StyleConstant.STYLE_TWO;
        webStyle = StyleConstant.WEB_STYLE_DAY_ONE + webHeadStyle + StyleConstant.WEB_STYLE_DAY_TWO;
        String body = webStyle + data;
//		body = body.replaceAll("<\\s*a\\s+([^>]*)\\s*>", "");
//		body = body.replace("#p#副标题#e#", "");
        super.loadDataWithBaseURL(baseUrl, body + StyleConstant.FOOT,
                mimeType, encoding, failUrl);
        if (!TextUtils.isEmpty(data)) {
            int size = UserConfigTools.textSize;
            changeTextSize(size + 1);
        }
    }


    /**
     * 缩小/缩小字体
     */
    public void changeTextSize(int fontSize) {

        if (fontSize < 0) {
            fontSize = 1;
        }
        if (fontSize > 5) {
            fontSize = 5;
        }
        if (fontSize == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(90);
            else
                getSettings().setTextSize(WebSettings.TextSize.SMALLEST);
        } else if (fontSize == 2) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(100);
            else
                getSettings().setTextSize(WebSettings.TextSize.SMALLER);
        } else if (fontSize == 3) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(110);
            else
                getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        } else if (fontSize == 4) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(120);
            else
                getSettings().setTextSize(WebSettings.TextSize.LARGER);
        } else if (fontSize == 5) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(140);
            else
                getSettings().setTextSize(WebSettings.TextSize.LARGEST);
        }


    }

    @Override
    protected void onSizeChanged(int w, int h, int ow, int oh) {
        super.onSizeChanged(w, h, ow, oh);
        if (mOnViewSizeChangedListener != null) {
            mOnViewSizeChangedListener.onViewSizeChanged(w, h, ow, oh);
        }
    }

    @Override
    public void loadUrl(String url) {
        if (isDestory || isToAlipay((ActivityUtils.getTopActivity()), this, url)) {
            return;
        }
        super.loadUrl(url);
    }


    public NewsDetailWebView(Context context) {
        super(context);
        init(context);
    }

    public NewsDetailWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public NewsDetailWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    /**
     * 初始化配置
     *
     * @param context
     */
    private void init(Context context) {
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.setLayoutParams(layoutParams);
        WebSettings settings = getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);// 提高渲染级别
        try {
            //这行代码内部有可能空指针
            settings.setJavaScriptEnabled(true);// 设置可以运行JS脚本
        } catch (Exception e) {
//            e.printStackTrace();
        }
        settings.setSupportZoom(false);// 用于设置webview禁止放大
        settings.setBuiltInZoomControls(false);
        // 暂不支持打开多窗口
        settings.setSupportMultipleWindows(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setDomStorageEnabled(true);
        settings.setStandardFontFamily("sans-serif");
        setWebChromeClient(new WebChromeClient());
        setDownloadListener(new CustomWebViewDownLoadListener(context));
        this.addJavascriptInterface(new JavascriptInterface(), "android");
    }


    /**
     * 替换html中的img标签
     *
     * @param content
     * @return
     */
    public String replaceImg(String content) {
        if (TextUtils.isEmpty(content)) {
            return content;
        }
        //用正则表达式匹配 IMG标签
        String regEx = "<img\\s[^>]+>";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(content);

        String s = "";
        String src;
        src = "src=\"file:///android_asset/loadpic_detail.png\"";
        //匹配img标签中的src属性的正则表达式
        String regEx_img = "(src|SRC)=(\"|\')(.*?)(\"|\')";
        Pattern imgPtn = Pattern.compile(regEx_img);

        Matcher imgmatcher;
        //<img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
        //循环匹配到了图片
        while (matcher.find()) {
            //循环替换图片
//			float width = 330;
//			int hight = 260;
            String oldStr = matcher.group();


            //得到匹配出来的图片地址
            imgmatcher = imgPtn.matcher(oldStr);
            String imgSrc = "";
            if (imgmatcher.find()) {
                try {
                    imgSrc = imgmatcher.group(3);//得到匹配到的图片地址
                } catch (ArrayIndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }

            String game = "";
            if (!TextUtils.isEmpty(oldStr) && oldStr.contains("isGame")) {
                game = " isGame = '1'";
            }


            //如果获取的地址不为空 ，则开始替换
            if (!TextUtils.isEmpty(imgSrc) && !TextUtils.isEmpty(content)) {
                s = "<img class=\"lazy\" " + src + " data-original=\"" + imgSrc + "\"" + game + "/>";
                content = content.replace(matcher.group(), s);
            }
        }
        return content;
    }

    /**
     * 网页跳转支付宝支付
     *
     * @param activity
     * @param webView
     * @param url
     * @return
     */
    public boolean isToAlipay(final Activity activity, final WebView webView, String url) {
        if (activity == null || activity.isFinishing()) {
            return false;
        }
        final PayTask task = new PayTask(activity);
        final String ex = task.fetchOrderInfoFromH5PayUrl(url);
        if (!TextUtils.isEmpty(ex)) {
            new Thread(new Runnable() {
                public void run() {
                    final H5PayResultModel result = task.h5Pay(ex, true);
                    if (!TextUtils.isEmpty(result.getReturnUrl())) {
                        activity.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                if (webView != null) {
                                    String uu = result.getReturnUrl();
                                    webView.loadUrl(uu);
                                }
                            }
                        });
                    }
                }
            }).start();
            return true;
        }
        return false;
    }

    /**
     * 滑动到底部(之中执行一次)
     */
    public void scrollBottom() {

        if (mContentHeight == 0) {
            //4.4以下的版本距离计算有误差所以我把
            if (AppTools.getSdkVertion() >= Build.VERSION_CODES.KITKAT) {
                mContentHeight = computeVerticalScrollRange();//(int) (getContentHeight()*getScaleY());
            } else {
                mContentHeight = computeVerticalScrollRange() - 1025;
            }
        }

        if (getScrollY() < mContentHeight) {
            //如果不在底端则滑至底部
            scrollTo(0, mContentHeight);
        }

    }

    @Override
    public void destroy() {
        try {
            loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            destroyDrawingCache();
            ViewGroup parent = (ViewGroup) getParent();
            if (parent != null) {
                parent.removeView(this);
            }
            removeAllViews();
            isDestory = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.destroy();
    }

    /**
     * 停止播放
     */
    public void stop() {
        //暂停视频
        onPause();
        try {
            getClass().getMethod("onPause").invoke(this, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 继续播放
     */
    public void play() {
        //继续播放视频
        try {
            getClass().getMethod("onResume").invoke(this, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当webview的大小发生变化时回调此接口
     */
    public interface OnViewSizeChangedListener {
        public void onViewSizeChanged(int w, int h, int ow, int oh);
    }


    /**
     * 返回是否被销毁
     *
     * @return
     */
    public boolean getIsDestory() {
        return isDestory;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /**
     * js 可调用的方法
     */
    @SuppressLint("JavascriptInterface")
    public class JavascriptInterface {

        @android.webkit.JavascriptInterface
        public void downloadGame(String gameJson) {
            try {
                if (StringUtils.isEmpty(gameJson)) return;
                com.blankj.utilcode.util.LogUtils.e(gameJson);
                GameContent gameContent = GsonUtils.fromJson(gameJson, GameContent.class);
                if (gameContent != null) {
                    boolean appInstalled = AppUtils.isAppInstalled(gameContent.getPackageName());
                    if (appInstalled) {
                        com.app.okhttplib.util.AppUtils.startUpApp(getContext(), gameContent.getIPackageName());
                    } else {
                        File unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, gameContent.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {//安装游戏
                            com.app.okhttplib.util.AppUtils.installAPP(getContext(), unInstallFile);
                        } else {
                            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(gameContent.getIUrl()));
                            if (downloadFileInfo == null) {
                                DownloadUtils.getSingleton().down(gameContent.getIUrl(), gameContent.getIPath(), gameContent);
                                GameDownloadActivity.insertGame(gameContent.getIGameId(), gameContent.getITitle(), gameContent.getIUrl(), gameContent.getIAppIcon(),
                                        gameContent.getIGameSummary(), gameContent.getIPackageName(), gameContent.getIPath(), gameContent.getISize());
                            } else {
                                String downloadStatus = downloadFileInfo.getDownloadStatus();
                                if (!DownloadStatus.DOWNLOADING.equals(downloadStatus)) {
                                    DownloadUtils.getSingleton().down(gameContent.getIUrl(), gameContent.getIPath(), gameContent);
                                    GameDownloadActivity.insertGame(gameContent.getIGameId(), gameContent.getITitle(), gameContent.getIUrl(), gameContent.getIAppIcon(),
                                            gameContent.getIGameSummary(), gameContent.getIPackageName(), gameContent.getIPath(), gameContent.getISize());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
